﻿using NAudio.Wave.SampleProviders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AudioSourceManager
{
    public abstract class IAudioSource : IDisposable
    {
        public string AudioPath;

        public Action<string> OnError;

        public Action<string> OnLog;

        protected IAudioSource()
        {
            AudioPath = string.Empty;
        }

        /// <summary>
        /// 根据路径匹配合适的播放源
        /// </summary>
        /// <param name="path"></param>
        /// <param name="audioSource"></param>
        /// <returns></returns>
        public static bool TryGetAudioPlayer(string path, out IAudioSource audioSource)
        {
            audioSource = null;
            List<IAudioSource> list = new List<IAudioSource>()
            {
                new AudioUdpStreamSource(),
                //new AudioHttpStreamSourceManager(),
                new AudioURLSource(),
                new AudioFileSource(),
            };
            foreach (IAudioSource manager in list)
            {
                if (manager.TryMatch(path))
                {
                    manager.AudioPath = path;
                    audioSource = manager;
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 得到统一的播放源格式
        /// </summary>
        /// <param name="sampleChannel"></param>
        /// <returns></returns>
        public bool TryGetSampleChannel(out SampleChannel sampleChannel)
        {
            sampleChannel = null;
            try
            {
                sampleChannel = GetSampleChannel();
                return true;
            }
            catch (Exception ex)
            {
                OnError?.Invoke(ex.Message);
                return false;
            };
        }

        /// <summary>
        /// 开始输出日志
        /// </summary>
        public void StartLog()
        {
            Task.Run(() =>
            {
                Thread.Sleep(500);
                OnLog?.Invoke(GetLog());
            });
        }

        /// <summary>
        /// 析构
        /// </summary>
        public abstract void Dispose();

        /// <summary>
        /// 尝试匹配路径
        /// </summary>
        /// <param name="Path"></param>
        /// <returns></returns>
        public abstract bool TryMatch(string Path);

        /// <summary>
        /// 开始读取状态
        /// </summary>
        /// <returns></returns>
        public abstract string GetLog();

        protected abstract SampleChannel GetSampleChannel();
    }
}
